﻿using System;
using System.ComponentModel.Composition;

namespace OperationPlugins.Models
{
    /// <summary>
    /// The default property matcher.
    /// </summary>
    [Export(typeof(IPropertyMatcher))]
    [DefaultPriority]
    internal sealed class DefaultPropertyMatcher : IPropertyMatcher
    {
        bool IPropertyMatcher.Match(IPropertyFilter filter, Type declaringType, string propertyName)
        {
            if (filter == null)
            {
                throw new ArgumentNullException("filter");
            }

            if (declaringType == null)
            {
                throw new ArgumentNullException("declaringType");
            }

            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName");
            }

            if (filter.DeclaringType != null && filter.DeclaringType.IsAssignableFrom(declaringType))
            {
                foreach (var pattern in filter.PropertyNames)
                {
                    // An asterix means that all properties are valid!
                    if (string.Equals("*", pattern))
                    {
                        return true;
                    }

                    // ...otherwise the property name must match the pattern.
                    if (string.Equals(propertyName, pattern, StringComparison.CurrentCulture))
                    {
                        return true;
                    }
                }
            }

            return false;
        }
    }
}
